from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework import permissions
from certificate_manager.models import *
from certificate_manager.serializers import *
from rest_framework.decorators import api_view
from rest_framework.response import Response
import json

class ReadOnly(permissions.BasePermission):
        def has_permission(self, request, view):
            return request.method in permissions.SAFE_METHODS


class NewsViewSet(viewsets.ModelViewSet):
        queryset = News.objects.all()
        serializer_class = NewsSerializer
        permission_classes = [permissions.IsAdminUser|ReadOnly]

        def list(self, request):
            param = request.query_params
            # 我们要在里面添加
            if 'cate' in param:
                count = int(param.get('count', 5))
                self.queryset = News.objects.order_by('-pk').filter(cate=param['cate'])[:count]
            else:
                self.queryset = News.objects.order_by('-pk')
            return super().list(request)

        def create(self, request, *args, **kwargs):
            is_many = isinstance(request.data, list)
            if not is_many:
                return super().create(request, *args, **kwargs)
            else:
                serializer = self.get_serializer(data=request.data, many=True)
                serializer.is_valid(raise_exception=True)
                self.perform_create(serializer)
                headers = self.get_success_headers(serializer.data)
                return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
